﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Net;
using System.IO;

namespace TvTipper.Core
{
    public class ImageManager
    {
        private static ImageManager s_instance;
        private LRUCache<string, Image> m_cache = new LRUCache<string, Image>(10);

        public static ImageManager Instance
        {
            get 
            {
                if (s_instance == null)
                {
                    s_instance = new ImageManager();
                }

                return s_instance;
            }
        }


        public Image getImage(string uri)
        {
            Image image;
            if (m_cache.TryGetValue(uri, out image))
            {
                return image;
            }

            image = GetFromUrl(uri);
            m_cache[uri] = image;
            return image;
        }

        private Image GetFromUrl(string url)
        {
            using (var wc = new WebClient())
            {
                wc.Proxy = null;
                try
                {
                    byte[] bFile = wc.DownloadData(url);
                    using (var ms = new MemoryStream(bFile))
                    {
                        return Image.FromStream(ms);
                    }
                }
                catch (WebException)
                {
                    //unrl problems;
                    return null;
                }
            }
        }
    }
}
